package lightrain.db.dialect.impl;


import org.springframework.util.StringUtils;

import lightrain.db.Model;
import lightrain.db.dialect.Dialect;

public abstract class AbstractDialect implements Dialect{
	
	

	public AbstractDialect() {
		super();
	}

	protected Model<?, ?> model;

	public AbstractDialect(Model<?, ?> model) {
		super();
		this.model = model;
	}

	public Model<?, ?> getModel() {
		return model;
	}

	public void setModel(Model<?, ?> model) {
		this.model = model;
	}
	
	
	@Override
	public String buildInsertSQL(Model<?,?> model) {
		StringBuilder sql = new StringBuilder();
		sql.append("INSERT INTO ");
		sql.append(model.getTableName());
		sql.append(" (");
		String values = " VALUES (";
		int i = 0;
		for (String key : model.getFieldNames()) {
			if(key.equals(model.getIdname())){
				if(!model.isIdAuto()){
					continue;
				}
			}
			if(i > 0){
				sql.append(" , ");
				values+=" , ";
			}
			sql.append(key);
			values+="?";
			i++;
		}
		values+=" ) ";
		sql.append(" )");
		sql.append(values);
		return sql.toString();
	}

	@Override
	public String buildInsertSQL() {
		return buildInsertSQL(this.model);
	}

	@Override
	public String bulidSelectSQL(Object...cols) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		if(cols.length > 0){
			for (int i = 0; i < cols.length; i++) {
				if(i > 0){
					sql.append(",");
				}
				sql.append(cols[i]);
			}
		}else{
			String[] columnNames = model.getColumnNames();
			if(columnNames.length > 0){
				for (int i = 0; i < columnNames.length; i++) {
					if(i > 0){
						sql.append(",");
					}
					sql.append(columnNames[i]);
				}
			}else{
				sql.append(" * ");
			}
		}
		sql.append(" FROM ");
		sql.append(model.getTableName());
		sql.append(StringUtils.isEmpty(model.getTableAlias())?"":(" "+model.getTableAlias()+" "));
		sql.append(model.getBuilder().toString());		
		return sql.toString();
	}

	@Override
	public String bulidLimitSelectSQL() {
		return " LIMIT ? , ? ";
	}

	@Override
	public String bulidDeleteSQL() {
		StringBuilder sql = new StringBuilder();
		sql.append("DELETE");
		sql.append(" FROM ");
		sql.append(model.getTableName());
		sql.append(" ");
		sql.append(model.getBuilder());
		return sql.toString();
	}

	@Override
	public String bulidUpdateSQL() {
		StringBuilder sql = new StringBuilder();
		sql.append("UPDATE ");
		sql.append(model.getTableName());
		sql.append(" SET ");
		for (String key : model.getFieldNames()) {
			if(!key.equals(model.getIdname())){
				model.getUpdateFieldMap().put(key, "?");	
			}
		}
		int i = 0;
		for (java.util.Map.Entry<String, Object> en : model.getUpdateFieldMap().entrySet()) {
			if(i > 0){
				sql.append(" , ");
			}
			
			sql.append(en.getKey());
			sql.append(" = ");
			sql.append(en.getValue());
			i++;
		}
		sql.append(model.getBuilder());
		return sql.toString();
	}
	
	
}
